package com.szgd.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.activiti.engine.impl.util.json.JSONArray;
import org.activiti.engine.impl.util.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.szgd.controller.BaseController;
import com.szgd.service.sys.DeptService;
import com.szgd.service.sys.UserService;
import com.szgd.util.AEncryptHelper;
import com.szgd.util.StringUtil;
import com.szgd.util.UserUtil;

/**
 * @author Administrator
 * 用户管理controller
 */
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {
    private static Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    DeptService deptService;
    @Autowired
    UserService userService;
    
    @RequestMapping("/toUserList")
    public ModelAndView toList(){
        System.out.println("--------    进入用户列表页面    ---------");
        ModelAndView mav = new ModelAndView("/sys/user/userList");
        List<Map<String,Object>> list = deptService.getDeptListRecord(null);
        mav.addObject("deptList",deptService.getDeptListRecord(null));
        return mav;
    }

    @RequestMapping("/toChangePwd")
    public ModelAndView toChangePwd() {
        ModelAndView mav = new ModelAndView("/sys/user/changePWD");
        return mav;
    }

    @RequestMapping("/gerUserTree")
    public void gerUserTree(HttpServletRequest request,HttpServletResponse response) {
        try {
            List<Map<String, String>> list = userService
                    .getUserTree(getMapParams(request));
            outJSONData(response,new JSONArray(list));
        } catch (java.lang.Exception e) {
            logger.error(e.getMessage());
        }
    }
    
    @RequestMapping("/getRoleTree")
    public void getRoleTree(HttpServletRequest request,HttpServletResponse response) {
        try {
            List<Map<String, String>> list = userService
                    .getRoleTree(getMapParams(request));
            outJSONData(response,new JSONArray(list));
        } catch (java.lang.Exception e) {
            logger.error(e.getMessage());
        }
    }

    public String logout(HttpServletRequest request){
        try{
            HttpSession session = request.getSession();
            session.removeAttribute("userInfo");
            session.removeAttribute("userRight");
            session.removeAttribute("userMenus");
            session.removeAttribute(UserUtil.USERINFOMATION);
        }catch(java.lang.Exception e){
            logger.error(e.getMessage());
        }
        return "logoutAction";
    }

    //用户列表页面
    public String toUserList(){
        return "userList";
    }

    public String selectUserPopup(){
        return "selectUser";
    }

    /**
     * 获取用户列表
     */
    @RequestMapping(value = "/getUserList")
    public void getUserList(HttpServletRequest request,HttpServletResponse response){
        outTableJSONData(response,userService.getUserList(getMapParams(request)));
    }


    /**
     * 获取用户列表
     */
    @RequestMapping(value = "/getApproverListByRoleAndDept")
    public void getApproverListByRoleAndDept(HttpServletRequest request,HttpServletResponse response,HttpSession session){
        Map<String,Object> params = getMapParams(request);
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("roleId",params.get("roleId"));
        paramMap.put("deptCd",params.get("deptCd"));
        List<Map<String,String>> userList = userService.getApproverListByRoleAndDept(paramMap);
        outTableJSONData(response,userList);
    }

    /**
     * 获取用户列表
     */
    @RequestMapping(value = "/getUserListByDept")
    public void getUserListByDept(HttpServletRequest request,HttpServletResponse response,HttpSession session){
        Map<String,Object> params = getMapParams(request);
        Map<String,Object> paramMap = new HashMap<>();
        //paramMap.put("roleId",params.get("roleId"));
        paramMap.put("deptCd",params.get("deptCd"));
        List<Map<String,String>> userList = userService.getUserListByDept(paramMap);
        outTableJSONData(response,userList);
    }

    /**
     * 获取所有的用户信息
     */
    public void getAllUserinfo(HttpServletRequest request,HttpServletResponse response){
        JSONObject json=getJson();
        List<Map<String,String>> list = userService.getAllUserInfo(null);
        json.put("aaData", new JSONArray(list));
        outJSONData(response,json);
    }

    /**
     * 分页查询角色授权的部门用户信息
     */
    public void getRoleGrantUsers(HttpServletRequest request,HttpServletResponse response){
        outTableJSONData(response,userService.getRoleGrantUsers(getMapParams(request)));
    }

    /**
     * 批量授权用户到角色组
     */
    public void batchGrantUserToRole(HttpServletRequest request,HttpServletResponse response){
        JSONObject json=getJson();
        json.put("success", true);
        json.put("message", "批量授权用户到角色组成功!");
        boolean mark = userService.batchGrantUserToRole(getMapParams(request));
        if(!mark){
            json.put("message", "批量授权用户到角色组失败!");
        }
        outJSONData(response,json);
    }

    /**
     * 从角色组移除用户
     */
    public void delUserAndRoleRelated(HttpServletRequest request,HttpServletResponse response){
        JSONObject json=getJson();
        json.put("success", true);
        json.put("message", "删除菜单用户成功!");
        try{
            boolean mark=userService.delUserAndRoleRelated(getMapParams(request))>0?true:false;
            if(!mark){
                json.put("message", "删除菜单用户成功!");
            }
        }catch(Exception e){
            logger.error("删除菜单用户成功！",e);
            json.put("message", "删除菜单用户成功!");
        }
        outJSONData(response,json);
    }
    //手动同步部门和用户数据
    @RequestMapping("/handsyn")
    public void handsyn(HttpServletRequest request,HttpServletResponse response){
        try{
            boolean markdept=deptService.synchro();
            boolean markuser=userService.synchro();
            String duStr = "";
            if (markdept && markuser)
                outJSONData(response,"{\"success\":true,\"msg\":\"同步部门用户成功!\"}");
            else{
                duStr += !markdept? "部门" : "";
                duStr += !markuser? "用户" : "";
                outJSONData(response,"{\"success\":false,\"msg\":\"同步" + duStr +"失败!\"}");
            }
        }catch(Exception e){
            logger.error("同步部门用户失败！",e);
        }
    }

    public void getUserByUserId(HttpServletRequest request,HttpServletResponse response){
        String userId = (String) getMapParams(request).get("USER_ID");
        outJSONData(response, new JSONObject(userService.getUserByUserId(userId)));
    }

    public void getZongDuiLd(HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> params=getMapParams(request);
        JSONObject json=getJson();
        List<Map<String,String>> list = null;
        try {
            list = userService.getZongDuiLd(params);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        json.put("aaData", new JSONArray(list));
        outJSONData(response,json);
    }
    public void getUserApproveRoleId_ByMenuRoleId(HttpServletRequest request,HttpServletResponse response){
        Map<String, Object> params=getMapParams(request);
        JSONObject json=getJson();
        json.put("success", true);
        json.put("message", " 查询该菜单下的用户流程角色成功!");
        String have_approveRoleId = "";
        try {
            have_approveRoleId = userService.getUserApproveRoleId_ByMenuRoleId(params);
            if(have_approveRoleId == null){
                have_approveRoleId = "";
            }
            json.put("have_approveRoleId",have_approveRoleId);
            request.setAttribute("have_approveRoleId", have_approveRoleId);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            json.put("message", "查询该菜单下的用户流程角色失败!");
        }
        outJSONData(response,json);
    }

    @RequestMapping("/setPassword")
    public void setPassword(HttpServletRequest request,HttpServletResponse response) {
        JSONObject json = getJson();
        try {

            Map<String, Object> map = this.getMapParams(request);
            String userId = String.valueOf(this.getUserId(request.getSession()));
            String loginId = (String)this.getUserMap(request.getSession()).get("username");	//用户map中username为loginId
            map.put("USER_ID", userId);
            map.put("USERPASSWORD",
                    AEncryptHelper.encrypt((String) map.get("oldpwd"),loginId));
            Map<String, String> loginUser = userService.login(map);
            if (loginUser == null) {
                json.put("message", "error");
            } else {
                String passwd = AEncryptHelper.encrypt((String) map.get("PASSWORD"), loginId);
                map.remove("PASSWORD");
                map.put("PASSWORD", passwd);
                userService.setPassword(map);
                json.put("message", "success");
            }
            outJSONData(response,json);
        } catch (java.lang.Exception e) {
            logger.error(e.getMessage());
            json.put("message", "exception");
        }
    }

    /**
     * 密码重置
     *
     * @throws Exception
     */
    @RequestMapping("/resetPwd")
    public void resetPwd(HttpServletRequest request,HttpServletResponse response) {
        JSONObject json = getJson();
        try {
            Map<String, Object> map = this.getMapParams(request);
            String passwd = AEncryptHelper.encrypt("123456",
                    (String) map.get("LOGIN_ID"));
            map.put("PASSWORD", passwd);
            userService.setPassword(map);
            json.put("message", "success");
        } catch (java.lang.Exception e) {
            logger.error(e.getMessage());
            json.put("message", "error");
        } finally {
            outJSONData(response,json);
        }
    }
    
    /**
	 * 新增用户
	 */
	@RequestMapping("/insertUser")
	public void insertUser(HttpServletRequest  request, HttpServletResponse response){
		JSONObject json=getJson();
		json.put("success", true);
		json.put("message", "添加用户成功!");
		try{
			Map<String, Object> map = getMapParams(request);
			Integer userId = userService.getNewUserId();
			map.put("USER_ID", userId);
			map.put("USER_PWD",AEncryptHelper.encrypt((String) map.get("USER_PWD"),(String) map.get("LOGIN_ID")));
			boolean mark=userService.insertUserAndRole(map)>0?true:false;
			if(!mark){
				json.put("message", "添加用户失败!");
			}
		}catch(Exception e){
			e.printStackTrace();
			json.put("message", "添加用户失败!");
		}
		
		outJSONData(response , json);
	}
	
	/**
	 * 更新用户
	 */
	@RequestMapping("/updateUser")
	public void updateUser(HttpServletRequest  request, HttpServletResponse response){
		JSONObject json=getJson();
		json.put("success", true);
		json.put("message", "更新用户成功!");
		try{
			Map<String, Object> map = getMapParams(request);
			map.put("USER_PWD",AEncryptHelper.encrypt((String) map.get("USER_PWD"),(String) map.get("LOGIN_ID")));
			boolean mark=userService.updateUser(map)>0?true:false;
			if(!mark){
				json.put("message", "更新用户失败!");
			}
		}catch(Exception e){
			e.printStackTrace();
			json.put("message", "更新用户失败!");
		}
		outJSONData(response , json);
	}
	
	/**
	 * 新增用户-从人员选择
	 */
	@RequestMapping("/insertUserFromPerson")
	public void insertUserFromPerson(HttpServletRequest  request, HttpServletResponse response){
		JSONObject json=getJson();
		try{
			Map<String, Object> map = getMapParams(request);
			String flag = map.get("FLAG_USER") == null ? "" : map.get("FLAG_USER").toString();
			String dept = map.get("DEPT_CD_USER") == null ? "" : map.get("DEPT_CD_USER").toString();
			String personIdStr = map.get("PERSONIDS") == null ? null : map.get("PERSONIDS").toString();
			if(StringUtil.isNotBlank(personIdStr) && personIdStr.endsWith(",")){
				personIdStr = personIdStr.substring(0,personIdStr.length() -1);
			}
			String msg = userService.insertUserFromPerson(flag, dept, personIdStr.split(","));
			json.put("success", true);
			json.put("message", "同步用户成功,"+msg);
		}catch(Exception e){
			e.printStackTrace();
			json.put("message", "同步用户失败!");
		}
		
		outJSONData(response , json);
	}

    @RequestMapping(value = "/delUser")
    @ResponseBody
    public Map<String,Object> delUser(@RequestBody HashMap<String, Object> paramMap, HttpServletRequest request, HttpServletResponse response) {
        try{
            userService.delUser(paramMap);
            return getSuccMap("删除成功");
        }catch (Exception e)
        {
            e.printStackTrace();
            logger.error("删除失败："+e.getMessage());
            return getSuccMap("删除失败："+e.getMessage());
        }

    }
    
    @RequestMapping("/toSiteUserList")
	public ModelAndView toWfRoleManPage(){

		ModelAndView mav = new ModelAndView("/sys/user/siteUserList");
		return mav;
	}
    
    /**
     * 获取所有站点
     * @param request
     * @param response
     */
    @RequestMapping("/getAllSite")
	public void getAllSite(HttpServletRequest  request, HttpServletResponse response){
		outTableJSONDataCommon(response,userService.getSiteAuth(getMapParams(request)));
	}
    
    /**
	 * 获得站点已授权用户列表
	 */
	@RequestMapping("/getSiteGrantUsers")
	public void getWfRoleGrantUsers(HttpServletRequest  request, HttpServletResponse response){
		outTableJSONData(response ,userService.getSiteGrantUsers(getMapParams(request)));
	}
	
	/**
	 * 获得用户已授权站点列表
	 */
	@RequestMapping("/getUserGrantSites")
	public void getUserGrantSites(HttpServletRequest  request, HttpServletResponse response){
		outTableJSONData(response ,userService.getUserGrantSites(getMapParams(request)));
	}
	
	/**
	 * 删除站点用户
	 */
	@RequestMapping("/deleteSiteUser")
	public void deleteSiteUser(HttpServletRequest  request, HttpServletResponse response){
		JSONObject json=getJson();
		json.put("success", true);
		json.put("message", "删除站点用户成功!");
		try{
			boolean mark=userService.deleteSiteUser(getMapParams(request))>0?true:false;
			if(!mark){
				json.put("message", "删除站点用户失败!");
			}
		}catch(Exception e){
			logger.error("删除站点用户失败！",e);
			json.put("message", "删除站点用户失败!");
		}
		outJSONData(response , json);
	}
	
	@RequestMapping("/batchGrantUserToWfRole")
	public void batchGrantUserToWfRole(HttpServletRequest  request, HttpServletResponse response){
		JSONObject json=getJson();
		json.put("success", true);
		json.put("message", "批量授权用户到站点成功!");
		boolean mark = userService.batchGrantUserToSite(getMapParams(request));
		if(!mark){
			json.put("success", false);
			json.put("message", "批量授权用户到站点失败!");
		}
		outJSONData(response , json);
	}
}
